<?php
/**
 * The base controller which is used by the Front and the Admin controllers
 */
use EasyWeChat\Foundation\Application;
class Base_Controller extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
        $this->load->database();
        $this->load->model('upload_m');
        $this->load->model('wxUser_m');
	}

    
}
class Wx_Controller extends Base_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->set_front_theme('wx');
        $data['viewmulu']=base_url('public/wx/');
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            if(empty($this->session->userdata("wechat_user"))){
                $func = !empty($this->router->fetch_method()) ? $this->router->fetch_method() : "index"; // 当前方法名
                if(!in_array($func,["wechatOauthBack"])){
                    $this->oauth(substr($_SERVER['REQUEST_URI'],1));
                }
            }
        }
        $this->load->vars($data);
    }

    /**
     * 微信登录验证
     * @param  string $action 回调的action
     * @return void
     */
    protected function oauth($callbackUrl) {
        // 未登录
        if (!$this->session->has_userdata("wechat_user")) {
            $config = [
                'app_id' => config_item("app_id"),
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'], //snsapi_base
                    'callback' => site_url('wx/home/wechatOauthBack'),
                ],
            ];
            $app = new Application($config);
            $oauth = $app->oauth;
            $this->session->set_userdata('target_url', base_url($callbackUrl));
            $oauth->redirect()->send();
        }
    }
    /**
     * 微信登录验证回调
     * @return void
     */
    public function wechatOauthBack() {

        $config = [
            'app_id' => config_item("app_id"),
            'secret' => config_item("app_secret"),
        ];
        $app = new Application($config);
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        $userArr = $user->toArray();
        $this->session->set_userdata("wechat_user", $userArr);
        $targetUrl = empty($this->session->userdata('target_url')) ? '/' : $this->session->userdata('target_url');
        // 微信用户信息入库
        $this->wxUser_m->unsubscribe($userArr);
        $openid = $this->session->userdata("wechat_user")['id'];
        // 查看用户是否已注册
        $wxuser = $this->wxUser_m->get_weixin_users_by_openid($openid);
        if(empty($wxuser['user_id'])){
            // 新用户数据入库
            $salt =get_salt();
            $admin = array(
                'user_name' => $wxuser['nickname'],
                'user_password' =>  password_dohash("123456",$salt),
                'user_salt' => $salt,
                'user_money'=> 0,
                'user_group'=> 4,
                'user_regtime' => time(),
                'user_logtime' => time(),
                'user_lock'=>0,
                'user_avatar'=>$wxuser["headimgurl"],
            );
            $agnet_id = $this->session->userdata('referee_id');
            if(!empty($agnet_id)){
                $admin['agent_id'] = $this->session->userdata('referee_id');
            }
            $this->user_m->register($admin);
            $new_id = $this->db->insert_id();
            $this->groupAcess_m->insert_user_access(['uid'=>$new_id,'group_id'=>4]);
            // 回写user_id
            $this->wxUser_m->update_weixin_users_by_openid($openid,["user_id"=>$new_id]);
            $user = $this->user_m->get_user_by_user_id($new_id);
        }else{
            $user = $this->user_m->get_user_by_user_id($wxuser['user_id']);
            $agnet_id = $this->session->userdata('referee_id');
            if(!empty($agnet_id) && empty($user['agent_id'])){
                $this->user_m->update_user($wxuser['user_id'],array('agent_id'=>$this->session->userdata('referee_id')));
            }
        }
        // 记录登录缓存
        $this->session->set_userdata('user_id',$user['user_id']);
        redirect($targetUrl);
    }
}

class Admin_Controller extends Base_Controller 
{
	function __construct()
	{
		parent::__construct();
		//载入模板
		$this->load->set_front_theme('manage');
		// 判断登录
		if(!$this->auth->is_login())
		{
			redirect(site_url());
		}
		// 链接数据库
		$this->load->database();
		if($this->session->userdata('user_id')){
			//取一个用户信息
			$data['user']=$this->user_m->get_user_by_user_id($this->session->userdata('user_id'));
			$data['user']['uname']=get_user_name($data['user']['user_name'],$data['user']['user_uname']);
			$data['user']['user_group_name']=$this->user_m->get_user_by_user_group($data['user']['user_group']);
			//获取头像
			$data['user']['big_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'big');
			$data['user']['middle_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'middle');
			$data['user']['small_avatar']=$this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'small');
		}else{
            redirect(site_url());
		}
		$uid = $this->session->userdata('user_id');
        $con = $this->router->fetch_class(); // 当前控制器
        if ($this->uri->segment(3) === FALSE)
        {
            $func = $this->router->fetch_method(); // 当前方法名
        }
        else
        {
            $func = $this->uri->segment(3);
        }
        // 获取当前菜单
        $current = $this->authRule_m->get_current($con,$func);

        $data['current']=$current[0];
        $userinfo = $this->user_m->get_user_with_group($uid);
        $menu_access_ids = $userinfo['rules'];
		// 检查访问权限
		$allow_controller_name = array('Upload');//放行控制器名称
        $allow_action_name = array();//放行函数名称
        if ($userinfo['group_id'] != 1 && !$this->auth->check($con . '/' . $func,
                $uid) && !in_array($con, $allow_controller_name) && !in_array($func,
                $allow_action_name)
        ) {
            show_message('没有访问权限',site_url('user/logout'),1);
        }
		// 获取登录用户的权限菜单
        if ($userinfo['group_id'] != 1) {
            $menu_where = "AND id in ($menu_access_ids)";
        } else {
            $menu_where = '';
        }
        $menu = $this->authRule_m->get_menu_by_auth($menu_where);
        $menu = $this->getMenu($menu);
        $data['menu']=$menu;
	
	 	$data['viewmulu']=base_url('public');
		$data['x_title'] = $this->config->item('site_short_name');
		$this->load->vars($data);
	}

   // 获取菜单
   protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();
        //修复父类设置islink=0，但是子类仍然显示的bug
        foreach( $items as $item ){
            if( $item['pid']==0 ){
                $father_ids[] = $item['id'];
            }
        }
        //----
        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            //修复父类设置islink=0，但是子类仍然显示的bug by shaoneng
            if( $item['pid']<>0 && !in_array( $item['pid'], $father_ids )){
                continue;
            }
            //----
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }
}
